window.Templates =
  HOME: 'main_page'
  NEW_GAME: 'new_game_page'
  SELECT_IMAGE: 'select_image'
  CAPTION_IMAGE: 'caption_image'
  OPTIONS: 'options_page'
  PICK_FRIENDS: 'pick_friends'
  VOTE: 'vote'
  VOTING_RESULTS: 'voting_results'

class Main_Controller_VM
  constructor: (inits) ->
    @title = ko.observable "Caption This!"  
    @template_name = ko.observable Templates.HOME
    #@template_name = ko.observable Templates.VOTE
    @display_page = => 
      return @template_name()
    
    @all_games = ko.observableArray []
    @current_game = ko.observable new game_state_vm(this)
    @game_counter = 1

    @selectImage = new select_image_vm(this)
    @captionImage = new caption_image_vm(this)
    @options = new options_vm(this)
    @vote = new vote_vm(this)
    @voting_results = new voting_results_vm(this)
    @pickFriends = new pick_friends_vm(this)
    
    @backQueue = ko.observableArray []    
    @backEnabled = ko.observable false
    
    @forwardQueue = ko.observableArray []
    
    @forwardEnabled = ko.observable false
    
      
  ##Other Bindings
  Refresh_JQM: (d) =>
    $(d).trigger("create")
    #v = $(d).find("ul")
    #v.listview 'refresh'
  
  Tap_NewGame: (d, e) =>
    @current_game new game_state_vm(this)
    @current_game().game_number = @all_games().length + 1
    @game_counter = @game_counter + 1
    @all_games().push @current_game()
    console.log "Added game #{@current_game().game_number}"
    @current_game().Play()
    
  Tap_Options: (d, e) =>
    this.Navigate(Templates.OPTIONS)
  ## TEMPORARY
  Tap_Continue: (d, e) =>
    @current_game().Play()
   
  Back: (d, e) =>
    if @backQueue().length != 0
      @forwardQueue().push(@template_name())
      @template_name @backQueue().pop()
      @forwardEnabled @forwardQueue().length > 0
      @backEnabled @backQueue().length > 0 
  
  Forward: (d, e) =>
    if @forwardQueue().length != 0
      @backQueue().push(@template_name())
      @template_name @forwardQueue().pop()
      @forwardEnabled @forwardQueue().length > 0
      @backEnabled @backQueue().length > 0
  
  Navigate: (template) =>
    @backQueue().push(@template_name())
    @template_name template
    @forwardEnabled false
    while @forwardQueue.length > 0
      @forwardQueue().pop()
    @backEnabled @backQueue().length > 0
    if @template_name() == Templates.SELECT_IMAGE
      window.setTimeout =>  
        @selectImage.Load_Swype()
      , 250
    
     
$(document).one 'app_init', (e, d) ->
  console.log "Loading Main Controller VM"
  ko.applyBindings new Main_Controller_VM()
  return